#! /usr/bin/env python
#coding=utf-8
#-*- coding: UTF-8 -*-
#coder  poorboy(叼毛) 
#url  http://www.caipiao365.vip


import time, datetime
import wx
import threading
import random
import os
import sys

sys.path.append("../") 
sys.path.append("../..")  

import net.DownVideo as DownVideo
from utils import commutils


#线程的基础类
class BaseThread(threading.Thread):
    
    def __init__(self,  win):
        threading.Thread.__init__(self)
        self.wind = win
        self.timeToQuit = threading.Event()
        self.timeToQuit.clear()
        self.messageCount = random.randint(10,20)
        self.messageDelay = 0.1 + 2.0 * random.random()
        
    def stop(self):
        self.timeToQuit.set()
        
    def AddDebugInfo(self, Msg):
        if self.wind.Debug == True:
            wx.CallAfter(self.wind.DbgMsg, u'{0}:{1}\r\n'.format(datetime.datetime.now().strftime("%H:%M:%S"), Msg))
            
    def AppendLog2Wind(self, log):
        wx.CallAfter(self.wind.LogMessageLn, u'{0}:{1}'.format(datetime.datetime.now().strftime("%H:%M:%S"), log))
        
    def run(self):   
        pass

    def FinshThread(self):
        pass


#获取搜索结果的线程类
class GetVideoItemsThread(BaseThread): 
    def __init__(self,  win):
        BaseThread.__init__(self, win)

    def run(self):        
        SerchKey = self.wind.SerchKey
        DowObj  = DownVideo.DownVideoMgr()
        uStrKey = unicode(SerchKey.decode('raw_unicode-escape').encode('utf-8'), 'utf-8')
        #print type(uStrKey)
        self.AppendLog2Wind(u'开始搜索[{0}],只获取前:{1}条'.format(uStrKey, self.wind.nPageSize))        
          
        nPage = 1

        for i in range(0, self.wind.nPageSize+1, 20):
            self.AppendLog2Wind(u'开始搜索第{0}页，{1} 到 {2}条'.format(nPage, i,  i + 20))
            vItem = DowObj.GetVideoItem(SerchKey, i) 
            self.AppendLog2Wind(u'第{0}页搜索完毕,一共获取了{1}条'.format(nPage, len(vItem) ) )
            wx.CallAfter(self.wind.AddVItems, vItem) 
            nPage = nPage + 1 

        self.FinshThread();

    def FinshThread(self): 
        wx.CallAfter(self.wind.GetVoideItemsThreadFinsh)
            
 #下载视频的线程类
class DownVideoThread(BaseThread): 
    tID = 0
    uDownStart = 0
    uDownEnd = 0

    uDownCount = 0
    uDownSuccess = 0
    DowObj  = None 

    def __init__(self,  win, _tID):        
        BaseThread.__init__(self, win)
        self.tID =  _tID
        self.DowObj  = DownVideo.DownVideoMgr()

        self.DowObj.SetDownBaseDir(self.wind.strSavePath)
        self.DowObj.SetFileSaveOver(self.wind.bIsOver)

        self.InitDownRange()        

    def InitDownRange(self):
        nCount = len(self.wind.Vitems)
        tNumber = self.wind.nThredNumber


        nDownSize = nCount / tNumber
        nMod = nCount % tNumber 

        self.uDownStart = ((self.tID-1)  * nDownSize) -1
        if(self.uDownStart < 0):
            self.uDownStart = 0 

        self.uDownEnd = self.uDownStart + nDownSize

        #最后一条线程多下几个
        if(self.tID == self.wind.nThredNumber):
            self.uDownEnd =  self.uDownEnd  + nMod

    def DoDownItem(self, index): 
            r = self.wind.Vitems[index]
            msgS = u"失败"
            bSuccess = False
            self.uDownCount = self.uDownCount + 1 

            if(self.DowObj.DownVideoItem(r)):
                msgS = u"成功"
                bSuccess = True
                self.uDownSuccess = self.uDownSuccess + 1
            
            wx.CallAfter(self.wind.DownItemFinsh, self.tID, bSuccess) 
            self.AppendLog2Wind(u'下载[{0}]完毕\r\n[{1}]下载:{2}'.format(r.url, r.title, msgS))
        
    def run(self): 
        self.AppendLog2Wind(u'线程[{0}]开始下载:{1}----{2}'.format(self.tID, self.uDownStart + 1 , self.uDownEnd + 1))
        for i in range(self.uDownStart, self.uDownEnd):
            self.DoDownItem(i) 
        self.FinshThread()

    def FinshThread(self): 
        wx.CallAfter(self.wind.DownThreadFinsh, self.tID, self.uDownCount, self.uDownSuccess)
        
def test():
    aa = object()
    
if __name__ == '__main__':
    test()
    
    